package com.example.testapplication;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;

public class JsonDemoActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_json2);
    }

    public void parse(View view){
        String json = getJsonString();
        try {
            JSONObject jsonObject = new JSONObject(json);
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray jsonArray = result.getJSONArray("data");
            for (int i = 0; i<jsonArray.length();i++){
                JSONObject obj = jsonArray.getJSONObject(i);
                String content = obj.getString("context");
                Toast.makeText(getApplicationContext(), content, Toast.LENGTH_SHORT).show();
            }
        }catch (JSONException e){
            e.printStackTrace();
        }

    }

    // 读取数据
    public String getJsonString(){
        AssetManager assetManager = getAssets();
        InputStream in = null;

        try{
            in = assetManager.open("jokes.json");
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            String json = new String(buffer);
            return json;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
}
